package license

import (
	"context"
	"encoding/json"

	v1 "gitee.com/liangziyisheng/caas-platform-mc/api/license/v1"
	"gitee.com/liangziyisheng/caas-platform-mc/internal/consts"
	"gitee.com/liangziyisheng/caas-platform-mc/internal/model/entity"
	"gitee.com/liangziyisheng/caas-platform-mc/internal/service"
	"gitee.com/liangziyisheng/caas-platform-mc/utility/cache"

	"github.com/gogf/gf/v2/errors/gerror"
)

func (c *ControllerV1) My(ctx context.Context, req *v1.MyReq) (res *v1.MyRes, err error) {
	// return nil, gerror.NewCode(gcode.CodeNotImplemented)
	tenantCode := ctx.Value(consts.TokenClaims.TenantCode).(string)
	in := &v1.MyInput{TenantCode: tenantCode, Status: req.Status}
	out, err := service.License().My(ctx, in)
	if err != nil {
		return nil, err
	}
	res = &v1.MyRes{Data: []v1.MyLic{}}
	if len(out.Data) > 0 {
		// 获取应用名称
		cc, _ := cache.NewCache()
		cache.InitCache(ctx, consts.InitialCacheKeys.AppsKey, false)
		val, err := cc.Get(ctx, consts.InitialCacheKeys.AppsKey)
		if err != nil {
			return nil, gerror.WrapCode(consts.GetCacheFailed, err)
		}
		cKey, ok := val.Val().(string)
		if !ok {
			return nil, gerror.WrapCode(consts.ParseCacheFailed, gerror.New("applications缓存解析出错"))
		}
		appMap := make(map[string]entity.App, 0)
		json.Unmarshal([]byte(cKey), &appMap)
		for _, v := range out.Data {
			res.Data = append(res.Data, v1.MyLic{
				Id:        v.Id,
				AppCode:   v.AppCode,
				AppName:   appMap[v.AppCode].Name,
				AppDesc:   appMap[v.AppCode].Description,
				UserLimit: v.UserLimit,
				Status:    v.Status,
				ExpiredAt: v.ExpiredAt,
			})
		}
	}
	return res, nil

}
